/*
 * Copyright 2005-2013 biz-united. All rights reserved.
 * Support: http://www.biz-united.com.cn
 * License: http://www.biz-united.com.cn/?page_id=5&act=3
 */
package net.biz.dao.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import net.biz.Filter;
import net.biz.Page;
import net.biz.Pageable;
import net.biz.dao.NativeBaseDao;
import net.biz.dao.OrderDao;
import net.biz.entity.Member;
import net.biz.entity.Order;
import net.biz.entity.Order.OrderStatus;
import net.biz.entity.Order.PaymentStatus;
import net.biz.entity.Order.ShippingStatus;
import net.biz.entity.OrderItem;
import net.biz.entity.Product;
import net.biz.util.ParamsUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.home766.dto.OrderBrandCountDTO;
import com.home766.entity.Shops;
import com.home766.util.StringUtil;

/**
 * Dao - 订单
 * 
 * @author BIZ Team
 * @version 3.0
 */
@Repository("orderDaoImpl")
public class OrderDaoImpl extends BaseDaoImpl<Order, Long> implements OrderDao {
	
	@Resource(name="nativeBaseDaoImpl")
	private NativeBaseDao nativeBaseDao;
	
	public Order findBySn(String sn) {
		if (sn == null) {
			return null;
		}
		String jpql = "select orders from Order orders where lower(orders.sn) = lower(:sn)";
		try {
			return entityManager.createQuery(jpql, Order.class).setFlushMode(FlushModeType.COMMIT).setParameter("sn", sn).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public List<Order> findList(Member member, Integer count, List<Filter> filters, List<net.biz.Order> orders) {
		if (member == null) {
			return Collections.<Order> emptyList();
		}
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
		return super.findList(criteriaQuery, null, count, filters, orders);
	}

	public Page<Order> findPage(Member member, Pageable pageable) {
		if (member == null) {
			return new Page<Order>(Collections.<Order> emptyList(), 0, pageable);
		}
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
		return super.findPage(criteriaQuery, pageable);
	}

	public Page<Order> findPage(Shops shops, Long adminId, Date beginDate,
			Date endDate, Integer schemeStatus, Integer schemePaymentStatus,
			Integer orderType, OrderStatus orderStatus,
			PaymentStatus paymentStatus, ShippingStatus shippingStatus,
			Boolean hasExpired, Pageable pageable,String shopName,Date createDate,Long provinceId,Long cityId,Long areaId,boolean flag) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		String properties = pageable.getSearchProperty();
		String propertiesValue = pageable.getSearchValue();
		if(shops!=null){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shops").<Long>get("id"), shops.getId()));
			restrictions = criteriaBuilder.or(restrictions, criteriaBuilder.equal(root.get("serviceShops").<Long>get("id"), shops.getId()));
		}
		if (orderStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}
		if(schemeStatus!=null){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("schemeStatus"), schemeStatus));
		}
		if(schemePaymentStatus!=null){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("schemePaymentStatus"), schemePaymentStatus));
		}
		if (orderType != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderType"), orderType));
		}
		if (paymentStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), paymentStatus));
		}
		if (shippingStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shippingStatus"), shippingStatus));
		}
		if (hasExpired != null) {
			if (hasExpired) {
				restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(), criteriaBuilder.lessThan(root.<Date> get("expire"), new Date()));
			} else {
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
			}
		}
		if(beginDate!=null){
			restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
		}
		if(endDate!=null){
			restrictions = criteriaBuilder.and(restrictions, root.get("createDate").isNotNull(),criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		if(flag){
			//销售报表
			if(beginDate==null && endDate==null){
				//默认当月第一天到当前时间
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal_1=Calendar.getInstance();//获取当前日期 
				cal_1.add(Calendar.MONTH,0);
				cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
				beginDate = cal_1.getTime();
				endDate = new Date();
				restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
				restrictions = criteriaBuilder.and(restrictions, root.get("createDate").isNotNull(),criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
			}
		}
		if(createDate!=null){
			restrictions = criteriaBuilder.and(restrictions, root.get("createDate").isNotNull(),criteriaBuilder.equal(root.<Date> get("createDate"), createDate));
		}
		if(StringUtils.isNotEmpty(properties) && StringUtils.isNotEmpty(propertiesValue)){
			if(properties.equals("shopsName")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.get("shops").<String>get("shopsName"),"%"+propertiesValue+"%"));
			}else if(properties.equals("shopsCode")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.get("shops").<String>get("shopsCode"),"%"+propertiesValue+"%"));
			}else if(properties.equals("serviceShopsName")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.get("serviceShops").<String>get("shopsName"),"%"+propertiesValue+"%"));
			}else if(properties.equals("serviceShopsCode")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.get("serviceShops").<String>get("shopsCode"),"%"+propertiesValue+"%"));
			}else if(properties.equals("sn")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("sn"), propertiesValue));
			}
			pageable.setSearchProperty(null);
			pageable.setSearchValue(null);
		}
		
		//如果创建时间不为空
		if(createDate != null){
			restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.equal(root.<Date> get("createDate"), createDate));
		}
		//门店不为空
		if(!StringUtil.isNullOrSpace(shopName)){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("shops").<String> get("shopsName"),"%"+shopName+"%"));
		}
		//区域信息不为空
		if(provinceId != null){
			if(cityId == null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("area").<String> get("treePath"),"%,"+provinceId+",%"));				
			}else if(cityId != null && areaId == null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("area").<String> get("treePath"),"%,"+cityId+",%"));				
			}else if(areaId != null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Long> get("area"),areaId));				
			}
		}
		
		criteriaQuery.where(restrictions);
		if(adminId==null){
			List<net.biz.Order> orders= pageable.getOrders();
//			List<Order> orders = pageable.getOrders();
			orders.add(net.biz.Order.desc("createDate"));
		}
		try {
			return super.findPage(criteriaQuery, pageable);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public Long count(OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		if (orderStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}
		if (paymentStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), paymentStatus));
		}
		if (shippingStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shippingStatus"), shippingStatus));
		}
		if (hasExpired != null) {
			if (hasExpired) {
				restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(), criteriaBuilder.lessThan(root.<Date> get("expire"), new Date()));
			} else {
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
			}
		}
		criteriaQuery.where(restrictions);
		return super.count(criteriaQuery, null);
	}

	public Long waitingPaymentCount(Member member) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderType"), ParamsUtil.CART_TYPE_NORMAL));
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.completed), criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.cancelled));
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("paymentStatus"), PaymentStatus.unpaid), criteriaBuilder.equal(root.get("paymentStatus"), PaymentStatus.partialPayment)));
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
		if (member != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
		}
		criteriaQuery.where(restrictions);
		Long temp=super.count(criteriaQuery, null);
		
		CriteriaBuilder criteriaBuilderScheme = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQueryScheme = criteriaBuilderScheme.createQuery(Order.class);
		Root<Order> rootScheme = criteriaQueryScheme.from(Order.class);
		criteriaQueryScheme.select(rootScheme);
		Predicate restrictionsScheme = criteriaBuilderScheme.conjunction();
		restrictionsScheme = criteriaBuilderScheme.and(restrictionsScheme, criteriaBuilderScheme.equal(rootScheme.get("orderType"), ParamsUtil.CART_TYPE_SCHEME));
		restrictionsScheme = criteriaBuilderScheme.and(restrictionsScheme, criteriaBuilderScheme.equal(rootScheme.get("schemeStatus"), ParamsUtil.SCHEME_STATUS_PAY));
		restrictionsScheme = criteriaBuilderScheme.and(restrictionsScheme, criteriaBuilderScheme.or(rootScheme.get("expire").isNull(), criteriaBuilderScheme.greaterThanOrEqualTo(rootScheme.<Date> get("expire"), new Date())));
		restrictionsScheme = criteriaBuilderScheme.and(restrictionsScheme, criteriaBuilderScheme.equal(rootScheme.get("schemePaymentStatus"), ParamsUtil.SCHEME_PAYMENT_STATUS_UNPAID));
		if (member != null) {
			restrictionsScheme = criteriaBuilderScheme.and(restrictionsScheme, criteriaBuilderScheme.equal(rootScheme.get("member"), member));
		}
		criteriaQueryScheme.where(restrictionsScheme);
		Long tempScheme=super.count(criteriaQueryScheme, null);
		return temp+tempScheme;
	}

	public Long waitingShippingCount(Member member) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.completed), criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.cancelled), criteriaBuilder.equal(root.get("paymentStatus"), PaymentStatus.paid), criteriaBuilder.equal(root.get("shippingStatus"), ShippingStatus.unshipped));
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
		if (member != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
		}
		criteriaQuery.where(restrictions);
		return super.count(criteriaQuery, null);
	}

	public BigDecimal getSalesAmount(Date beginDate, Date endDate) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal> get("amountPaid")));
		Predicate restrictions = criteriaBuilder.conjunction();
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed));
		if (beginDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
		}
		if (endDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		criteriaQuery.where(restrictions);
		return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
	}

	public Integer getSalesVolume(Date beginDate, Date endDate) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Integer> criteriaQuery = criteriaBuilder.createQuery(Integer.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(criteriaBuilder.sum(root.join("orderItems").<Integer> get("shippedQuantity")));
		Predicate restrictions = criteriaBuilder.conjunction();
		restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed));
		if (beginDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
		}
		if (endDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		criteriaQuery.where(restrictions);
		return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
	}

	public void releaseStock() {
		String jpql = "select orders from Order orders where orders.isAllocatedStock = :isAllocatedStock and orders.expire is not null and orders.expire <= :now";
		List<Order> orders = entityManager.createQuery(jpql, Order.class).setParameter("isAllocatedStock", true).setParameter("now", new Date()).getResultList();
		if (orders != null) {
			for (Order order : orders) {
				if (order != null && order.getOrderItems() != null) {
					for (OrderItem orderItem : order.getOrderItems()) {
						if (orderItem != null) {
							Product product = orderItem.getProduct();
							if (product != null) {
								entityManager.lock(product, LockModeType.PESSIMISTIC_WRITE);
								product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
							}
						}
					}
					order.setIsAllocatedStock(false);
				}
			}
		}
	}

	@Override
	public List<Order> getOrderList(Shops shops,Long adminId,Date beginDate,Date endDate,Integer schemeStatus, Integer orderType,
			OrderStatus orderStatus, PaymentStatus paymentStatus,
			ShippingStatus shippingStatus, Boolean hasExpired,Pageable pageable) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		String properties = pageable.getSearchProperty();
		String propertiesValue = pageable.getSearchValue();
		if(adminId!=null){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shops").<Long>get("admin"), adminId));
		}
		if (orderStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}
		if(schemeStatus!=null){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("schemeStatus"), schemeStatus));
		}
		if (orderType != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderType"), orderType));
		}
		if (paymentStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), paymentStatus));
		}
		if (shippingStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shippingStatus"), shippingStatus));
		}
		if (hasExpired != null) {
			if (hasExpired) {
				restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(), criteriaBuilder.lessThan(root.<Date> get("expire"), new Date()));
			} else {
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
			}
		}
		if(beginDate!=null){
			restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
		}
		if(endDate!=null){
			restrictions = criteriaBuilder.and(restrictions, root.get("createDate").isNotNull(),criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		if(StringUtils.isNotEmpty(properties) && StringUtils.isNotEmpty(propertiesValue)){
			if(properties.equals("shopsName")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get("shops").<String>get("shopsName"),"%"+propertiesValue+"%"));
			}else if(properties.equals("shopsCode")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get("shops").<String>get("shopsCode"),"%"+propertiesValue+"%"));
			}else if(properties.equals("serviceShopsName")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get("serviceShops").<String>get("shopsName"),"%"+propertiesValue+"%"));
			}else if(properties.equals("serviceShopsCode")){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get("serviceShops").<String>get("shopsCode"),"%"+propertiesValue+"%"));
			}
			pageable.setSearchProperty(null);
			pageable.setSearchValue(null);
		}
		criteriaQuery.where(restrictions);
		return super.findList(criteriaQuery,0,60000,null,null);
	}

	@Override
	public int updateServiceShop(Long id, Shops shops) {
		// TODO Auto-generated method stub
		String hql=" update Order o set o.serviceShops=:shops where id=:id ";
		return entityManager.createQuery(hql).setFlushMode(FlushModeType.COMMIT).setParameter("shops", shops).setParameter("id", id).executeUpdate();
	}
	
	/***
	 * 订单报表集合数据查询
	 * @param pageable
	 * @param shopName
	 * @param createDate
	 * @param provinceId
	 * @param cityId
	 * @param areaId
	 * @return
	 */
	public List<Order> findExportList(String shopName,Date beginDate,Date endDate,Date createDate,Long provinceId,Long cityId,Long areaId) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		//如果创建时间不为空
		if(createDate != null){
			restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.equal(root.<Date> get("createDate"), createDate));
		}
		if(beginDate==null && endDate==null){
			//默认当月第一天到当前时间
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal_1=Calendar.getInstance();//获取当前日期 
			cal_1.add(Calendar.MONTH,0);
			cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
			beginDate = cal_1.getTime();
			endDate = new Date();
		}
		if(beginDate!=null){
			restrictions = criteriaBuilder.and(restrictions,root.get("createDate").isNotNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("createDate"), beginDate));
		}
		if(endDate!=null){
			restrictions = criteriaBuilder.and(restrictions, root.get("createDate").isNotNull(),criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		//门店不为空
		if(!StringUtil.isNullOrSpace(shopName)){
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("shops").<String> get("shopsName"),"%"+shopName+"%"));
		}
		//区域信息不为空
		if(provinceId != null){
			if(cityId == null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("area").<String> get("treePath"),"%,"+provinceId+",%"));				
			}else if(cityId != null && areaId == null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.join("area").<String> get("treePath"),"%,"+cityId+",%"));				
			}else if(areaId != null){
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Long> get("area"),areaId));				
			}
		}
		criteriaQuery.where(restrictions);
		return super.findList(criteriaQuery, null, null, null, null);
	}
	
	/**
	 * 统计订单中各品牌的数量
	 * @return
	 */
	@Override
	public List<OrderBrandCountDTO> countOrderBrandNumber() {
		StringBuffer sql = new StringBuffer();
		sql.append("  SELECT                          ");
		sql.append("    xp.brand,                     ");
		sql.append("    COUNT(1) AS count_number      ");
		sql.append("  FROM xx_order_item item         ");
		sql.append("    LEFT JOIN xx_product xp       ");
		sql.append("      ON xp.id = item.product     ");
		sql.append("    LEFT JOIN xx_brand xb         ");
		sql.append("      ON xb.id = xp.brand         ");
		sql.append("  WHERE item.order_type = 1       ");
		sql.append("      AND xp.brand IS NOT NULL    ");
		sql.append("  GROUP BY brand                  ");
		Map<String, Object> map = new HashMap<String, Object>();
		return nativeBaseDao.findList(sql.toString(), map, OrderBrandCountDTO.class);
	}
}